package com.haoshuang.zhouzhoubang.ui.activity

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityPersonalHomeBinding
import com.haoshuang.zhouzhoubang.model.bean.MyInfoBean2
import com.haoshuang.zhouzhoubang.ui.dialog.MarkDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowSkillListDialog
import com.haoshuang.zhouzhoubang.ui.page.home.settings.skill.record.ServiceLabelAdapter2
import com.haoshuang.zhouzhoubang.ui.vm.PersonalHomeViewModel
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import okhttp3.internal.notify
import java.io.ByteArrayOutputStream


/**
 *  师傅个人主页界面
 */
class PersonalHomeActivity : BaseVMActivity<PersonalHomeViewModel, ActivityPersonalHomeBinding>() {
    private var infoBean: MyInfoBean2? = null

    val data = arrayListOf<String>()
    /**recycleview列表适配器*/
    private val mrvSkillAdapter = ServiceLabelAdapter2(data)
    override fun initView(savedInstanceState: Bundle?) {
        val flexboxLayoutManager = FlexboxLayoutManager(this)    // 创建布局管理者
        flexboxLayoutManager.apply {
            flexDirection = FlexDirection.ROW   //设置水平方向。从左到右
            //flexWrap 默认情况下 Flex 跟 LinearLayout 一样，都是不带换行排列的，但是flexWrap属性可以支持换行排列。
            flexWrap = FlexWrap.WRAP    //按正常方向换行
            //justifyContent 属性定义了项目在主轴上的对齐方式。
            justifyContent = JustifyContent.FLEX_START  //项目在主轴上对齐方式，例如上面定义水平方向，就是水平方向对齐方式
            alignItems = AlignItems.CENTER  //项目在交叉口对齐方式，因为上面定义水平方向，则为在垂直方向对齐方式
        }

        binding.tvAllSkill.clickWithTrigger {
            val list = infoBean?.service_skills?.split(",")?.toMutableList() ?: mutableListOf()
            XPopup.Builder(mActivity)
                .asCustom(ShowSkillListDialog(mActivity, list))
                .show()
        }

        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "个人主页"

            rvSkill.layoutManager = flexboxLayoutManager    // 给recycleview设置布局管理者
            rvSkill.adapter = mrvSkillAdapter    // 给recycleview设置适配器对象
            tvBj.clickWithTrigger {
                XPopup.Builder(this@PersonalHomeActivity)
                    .asCustom(MarkDialog(this@PersonalHomeActivity) {
                        vm.getData2("to_user_id" to user_id, "mark" to it)
                    })
                    .show()
            }
        }
    }

    fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray? {
        val output = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
        if (needRecycle) {
            bmp.recycle()
        }
        val result = output.toByteArray()
        try {
            output.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }

    var user_id = 0
    override fun initData() {
        user_id = intent.getIntExtra("user_id", 0)
        if (user_id == 0) {
            vm.getData()
            binding.llRemark.gone()
            binding.tvEdit.visible()
        } else {
            binding.llRemark.visible()
            vm.getData("user_id" to user_id)
            binding.tvEdit.gone()
        }


    }

    override fun startObserve() {
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("添加成功")
                if (user_id == 0) {
                    vm.getData()
                    binding.llRemark.gone()
                    binding.tvEdit.visible()
                } else {
                    binding.llRemark.visible()
                    vm.getData("user_id" to user_id)
                    binding.tvEdit.gone()
                }
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                infoBean = it;
                if (it != null) {
                    binding.apply {
                        var list = it.service_skills.split(",").toMutableList()
                        llSkill.visibleOrGone(list.isNotEmpty())
                        if (list.size > 6){
                            list = list.subList(0, 6)
                        }
                        data.clear()
                        data.addAll(list)
                        mrvSkillAdapter.notifyDataSetChanged()
                        ivHead.load(it.avatar, R.mipmap.rl)
                        textView30.text = it.phone
                        textView9.text = it.nickname
                        tvMark.text = it.mark
                        tvNum.text = it.complete_order_num
                        tvNum2.text = it.applause_rate
                        /// 入驻时长
                        tvNum3.text = it.master_settle_time
                        /// 常用位置
                        tvAddress.text = "${it.service_area}"
                        textView34.visible()
                        textView35.visible()
                        tvTouBao.visible()
                        if (it?.is_authentication == "1") {
                            textView34.setBackgroundResource(R.drawable.bg_4h)
                            textView34.setText("已实名")
                        } else {
                            textView34.setBackgroundResource(R.drawable.bg_4d)
                            textView34.setText("未实名")
                        }
                        if (it?.report == "1") {
                            textView35.setBackgroundResource(R.drawable.recatangle_00b7f5_4dp)
                            textView35.setText("已体检")
                        } else {
                            textView35.setBackgroundResource(R.drawable.bg_4d)
                            textView35.setText("未体检")
                        }
                        if (it.insurance_status == "0"){
                            //
                            tvTouBao.text = "未投保"
                            tvTouBao.isSelected = false
                        }else if (it.insurance_status == "1"){
                            tvTouBao.text = "已投保"
                            tvTouBao.isSelected = true
                        }else{
                            tvTouBao.text = "已过期"
                            tvTouBao.isSelected = false
                        }

                        // 年龄性别
                        tvAgeGender.text = "年龄：${it.age} 性别：${it.sex}"
                        tvShengxiao.text = "属相: ${it.shengxiao}"
                        tvNation.text = "民族: ${it.nation}"
                        tvConstellation.text = "星座: ${it.constellation}"
                        tvCity.text = "籍贯: ${it.native_place}"
                        tvSelfIntroduction.text = it.self_introduction
                    }
                }
            }
        }
    }

}